<?php
use Base\AdminController;
use Illuminate\Support\Str;

class MessageController extends AdminController
{
    protected string $table = 'messages';

    protected string $model = "message";

    /**
     * @return void
     */
    protected function update(): void
    {
        DB::beginTransaction();
        try {
            $params  = Request::all();
            unset($params['user_id']);
            $params['created_at'] = date("Y-m-d H:i:s");
            if (DB::schema()->hasColumn($this->table, "org_id")) {
                $params['org_id'] = $this->org['id'];
            }
            if (DB::schema()->hasColumn($this->table, "user_id")) {
                $params['user_id'] = $this->member_id;
            }
            $params['uuid'] = (string)Str::uuid();
            $res =  App::make($this->getModelMame())->insertGetId($params);
            $info =  App::make($this->getModelMame())->where('id',$res)->first();
            $insert = [];
            foreach (Request::input("user_id") as $vo) {
                $params['user_id'] = $vo;
                $receive_id = MessageReceiveModel::insertGetId($params);
                $insert[] = [
                    'user_id'=>$vo,
                    'message_id'=>$info['id'],
                    'receive_id'=>$receive_id,
                    'created_at'=>date("Y-m-d H:i:s")
                ];
            }
            MessageUserModel::insert($insert);
            DB::commit();
            $this->apiSuccess( $info->toArray(),"发送成功",20000);
        } catch (Exception $exception) {
            DB::rollBack();
            Log::$customFileName = LOG_PATH."/errors/";
            Log::error($exception->getMessage().$exception->getTraceAsString());
            $this->apiError($exception->getMessage());
        }
    }

    /**
     * 查看
     * @return void
     */
    public function infoAction(): void
    {
        try {
            $info = App::make($this->getModelMame())->where('id', Request::input("ids"))->first();
            if (!$info) $this->apiError("数据不存在");
            $info['lst'] = MessageUserModel::query()->join("users","id","=","user_id")
                ->where('message_id',$info['id'])
                ->selectRaw("message_users.status,users.nickname")
                ->get()->toArray();
            $this->apiSuccess($info,"获取成功",20000);
        } catch (Exception $exception) {
            Log::$customFileName = LOG_PATH."/errors/";
            Log::error($exception->getMessage().$exception->getTraceAsString());
            $this->apiError($exception->getMessage());
        }
    }
}
